<template>
  <div class="dynamic-background">
    <el-row class="login-container" justify="center" align="middle">
      <el-card class="login-card" :body-style="{ padding: '20px' }">
        <div class="title">人力资源管理系统</div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          class="demo-ruleForm"
          :rules="rules"
        >
          <el-form-item prop="userName">
            <el-input
              v-model="loginForm.userName"
              placeholder="邮箱"
              :prefix-icon="UserFilled"
            ></el-input>
          </el-form-item>
          <el-form-item prop="passWord" v-if="loginType === 'password'">
            <el-input
              v-model="loginForm.passWord"
              type="password"
              placeholder="密码"
              :prefix-icon="Lock"
            ></el-input>
          </el-form-item>
          <el-form-item prop="validCode" v-if="loginType === 'code'">
            <el-input
              v-model="loginForm.validCode"
              placeholder="验证码"
              :prefix-icon="Lock"
            >
              <template #append>
                <span @click="countdownChange">{{ countdown.validText }}</span>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item style="display: flex; justify-content: flex-end">
            <el-radio-group v-model="loginType" style="margin-left: 200px"  @change="handleLoginTypeChange" >
              <el-radio label="password">密码登录</el-radio>
              <el-radio label="code">验证码登录</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item>
            <el-button
              type="primary"
              :style="{ width: '100%' }"
              @click="submitForm(loginFormRef)"
            >
              登录
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>
    </el-row>
  </div>
</template>

<script setup>
import { UserFilled, Lock } from '@element-plus/icons-vue'
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { loginbyPwd,loginbyValidCode } from '@/api/login'

const router = useRouter()

const loginForm = reactive({
  userName: '',
  passWord: '',
  validCode: ''
})
const loginType = ref('password') // 默认为密码登录

const countdown = reactive({
  validText: '获取验证码',
  time: 60
})
let flag = false



// 验证码倒计时
const countdownChange = async() => {
  if (flag) return
  const phoneReg =
     /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
  if (!loginForm.userName || !phoneReg.test(loginForm.userName)) {
    return ElMessage({
      message: '请检查邮箱是否正确'
    })
  }
  const time = setInterval(() => {
    if (countdown.time <= 0) {
      countdown.time = 60
      countdown.validText = '获取验证码'
      flag = false
      clearInterval(time)
    } else {
      countdown.time -= 1
      countdown.validText = `剩余${countdown.time}s`
    }
  }, 1000)
  flag = true

  //  发送验证码 
  const res = await loginbyValidCode(loginForm)
  if(res.code===200){
      ElMessage.success('发送成功')
  }else{
    ElMessage.warning('发送失败')
    
  }


}
//  判断短信还是密码
const loginChoose = ref(1)
const loginFormRef = ref()
//选择登录方式
const handleLoginTypeChange = (value)=>{
  console.log(`当前选中的登录类型是: ${value}`);
  if (value === 'password') {
        // 处理密码登录
        loginChoose.value = 1
      } else if (value === 'code') {
        // 处理验证码登录
        loginChoose.value = 0
  }
}

//表单提交
const submitForm = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async(valid, fields) => {
    if (valid) {
      //密码选择
      await handleLoginTypeChange()
      
      if(loginChoose.value === 0 ) {
        loginForm.passWord=''
        const res = await loginbyPwd ({userName:loginForm.userName,validCode:loginForm.validCode})
        console.log(res);
        if(res.code === 200){
          ElMessage.success('验证码登录成功')
          localStorage.setItem('token',res.data.token)
          localStorage.setItem('currentUser',JSON.stringify(res.data.currentUser))
          router.push('/')
        }else{
          ElMessage.warning('邮箱或验证码错误，登录失败')
          
        }     
      }else{
        const res = await loginbyPwd ({userName:loginForm.userName,passWord:loginForm.passWord})
        console.log(res);
        if(res.code === 200){
          ElMessage.success('密码登录成功')
          localStorage.setItem('token',res.data.token)
          localStorage.setItem('currentUser',JSON.stringify(res.data.currentUser))
          router.push('/')
        }else{
          ElMessage.warning('邮箱或密码错误，登录失败')
        }
      }
      //登录
    
    
    } else {
      console.log('error submit!', fields)
    }
  })
}

</script>

<style lang="less" scoped>
.login-container {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100vh;
}
.login-container {
  display: flex;
  // justify-content: center;
  // align-items: center;
  height: 100vh;
  background-image: url('../../assets/login-head.png');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
.login-card {
  width: 480px;
  margin-left: 450px;
  margin-top: -150px;
}

.title {
  text-align: center;
  font-size: 24px;
  font-weight: bold;
  margin-bottom: 20px;
}
// .el-form {
//   .el-form-item {
//     .el-form-item__content {
//       display: flex;
//       justify-content: flex-end;
//       align-items: center;
//     }
//   }
// }
</style>
